<?php
/**
 * Created by PhpStorm.
 * User: yellow
 * Date: 2019/5/17
 * Time: 14:00
 */

namespace app\common\service;


use app\common\service\code\ErrorCode;
use think\facade\Config;

class WeixinService
{

    private $wxBizDataCrypt;
    private $appId;
    private $secret;

    public function __construct()
    {
        require_once '../extend/wx_aes/wxBizDataCrypt.php';
        $this->appId = Config::get('xcx_appid');
        $this->secret = Config::get('xcx_secret');
    }

    /**
     * 解密数据
     * @param $sessionKey
     * @param $encryptedData
     * @param $iv
     */
    public function decodeData($sessionKey, $encryptedData, $iv){
        $this->wxBizDataCrypt = new \WXBizDataCrypt($this->appId, $sessionKey);
        $errCode = $this->wxBizDataCrypt->decryptData($encryptedData, $iv, $data);
        if ($errCode == 0){
            return ajaxArr(ErrorCode::$SUCCESS, 'success', $data);
        } else{
            return ajaxArr($errCode, '微信解密错误'.$errCode);
        }
    }

    /**
     * 微信登录
     * 1.换取sessionKey会话钥匙
     * 2.获取用户登录openid和unionid
     */
    public function codeTSession($jscode){
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=".$this->appId."&secret=".$this->secret."&js_code=".$jscode."&grant_type=authorization_code";
        $sessionData = file_get_contents($url);
        $sessionData = json_decode($sessionData, true);
        if ($sessionData['errcode'] == 0){
            return ajaxArr(ErrorCode::$SUCCESS, 'success', $sessionData);
        } else{
            return ajaxArr($sessionData['errcode'], $sessionData['errmsg']);
        }
    }

}